﻿using IdentityModel.Client;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace WYFast.Framework.Api
{

    public class LoginController : ApiControllerBase
    {
        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="Username"></param>
        /// <param name="Password"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Login(string Username, string Password)
        {
            //从元数据中发现客户端
            var disco = await DiscoveryClient.GetAsync("http://localhost:5000");

            if (Username != "admin" && Password != "admin")
            {
                return BadRequest();
            }

            var claim = new Claim[]{
                    new Claim(ClaimTypes.Name,"admin"),
                    new Claim(ClaimTypes.Role,"admin")
                };

            //对称秘钥
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("Hello-key-----api"));
            //签名证书(秘钥，加密算法)
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            //生成token  [注意]需要nuget添加Microsoft.AspNetCore.Authentication.JwtBearer包，并引用System.IdentityModel.Tokens.Jwt命名空间
            var token = new JwtSecurityToken("ExampleIssuer", "ExampleIssuer", claim, DateTime.Now, DateTime.Now.AddMinutes(30), creds);

            return Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token) });
        }
    }
}
